<template>
  <!-- <a-tabs v-model:active-key="currentTab" type="rounded">
    <a-tab-pane :key="item.value" :title="item.label" v-for="item in tabsList" />
  </a-tabs> -->
  <div class="service-box">
    <!-- 电子合同业务展示 -->
    <template
      v-if="
        enterpriseDetail.config.econtractFirstOpen === 1 &&
        enterpriseDetail.config.econtractEnabled === 1 &&
        enterpriseDetail.config.authenticatinStatus === 1 &&
        enterpriseDetail.config.authorizationStatus === 1
      "
    >
      <div class="service-view" v-if="status == 'view'">
        <basic-info-descriptions :data="basicInfo">
          <template #signType>
            {{ enterpriseDetail.config.signType === 1 ? '手动签署' : '自动签署' }}
            &nbsp;&nbsp;
            <!-- <a-button
              type="primary"
              size="mini"
              v-if="
                enterpriseDetail.config.automaticState === -1 ||
                enterpriseDetail.config.automaticState === 0 ||
                enterpriseDetail.config.automaticState === 2
              "
              :disabled="enterpriseDetail.config.automaticState === 2"
              @click="onApplyFor"
            >
              {{ enterpriseDetail.config.automaticState === 2 ? '自动签署授权中' : '申请自动签署' }}
            </a-button> -->
            <a-button type="primary" size="mini" v-if="enterpriseDetail.config.automaticState !== 1" @click="onApplyFor">
              申请自动签署
            </a-button>
          </template>
        </basic-info-descriptions>
      </div>
      <div class="service-edit" v-else>
        <page-form :model="form" ref="formRef" layout="vertical" :gutter="24">
          <page-form-row :gutter="24" v-show="currentTab == 0">
            <page-form-item label="开通付费版合同服务" class="mb-0">
              <div class="signType">
                <a-radio-group v-model="form.config.userEcontractEnabled">
                  <a-radio :value="1">开启</a-radio>
                  <a-radio :value="0">关闭</a-radio>
                </a-radio-group>
              </div>
            </page-form-item>
            <page-form-item label="支持的服务类型" class="mb-0">
              <a-checkbox-group v-model="form.userContractServiceType" :disabled="form.config.userEcontractEnabled === 0">
                <a-checkbox :value="0" v-if="form.contractServiceType.includes(0)">自驾短租</a-checkbox>
                <a-checkbox :value="1" v-if="form.contractServiceType.includes(1)">自驾长租</a-checkbox>
              </a-checkbox-group>
            </page-form-item>

            <page-form-item label="签约方式" class="mb-0">
              <template v-if="enterpriseDetail.config.automaticState !== 1">
                手动签署&nbsp;&nbsp;
                <a-button type="primary" size="mini" :disabled="form.config.automaticState === 2" @click="onApplyFor">
                  申请自动签署
                </a-button>
              </template>
              <a-radio-group v-else v-model="form.config.signType" :disabled="form.config.userEcontractEnabled === 0">
                <a-radio :value="0">自动签署</a-radio>
                <a-radio :value="1">手动签署</a-radio>
              </a-radio-group>
            </page-form-item>
          </page-form-row>
        </page-form>
      </div>
      <a-divider />
      <template v-if="currentTab == '0'">
        <div class="logo-title">账户信息</div>
        <a-alert>
          <template #icon>
            <icon-exclamation-circle />
          </template>
          账户余额过少时，为避免业务受到影响，请提前联系工作人员充值
        </a-alert>
        <div class="descriptions-box">
          <div class="descriptions-item-box">
            <div class="descriptions-item">
              <div class="label">账户余额</div>
              <div class="item">
                <div class="num blue">
                  {{ enterpriseDetail.config.accountBalance || '-' }}
                </div>
                <div class="mb-1">&nbsp;元</div>
              </div>
            </div>
            <div class="descriptions-item">
              <div class="label">
                总充值金额&nbsp;&nbsp;
                <a-button v-if="isShowLogs" type="outline" size="mini" @click="openModal">查看充值记录</a-button>
              </div>
              <div class="item">
                <div class="num">{{ enterpriseDetail.config.allRechargeAmount || '-' }}</div>
                <div class="mb-1">&nbsp;元</div>
              </div>
            </div>
          </div>
          <a-divider direction="vertical" class="h-8" />
          <div class="descriptions-item-box">
            <div class="descriptions-item">
              <div class="label">企业合同收费标准</div>
              <div class="item">
                <div class="num">{{ enterpriseDetail.config.enterpriseContract || '-' }}</div>
                <div class="mb-1">&nbsp;元</div>
              </div>
            </div>
            <div class="descriptions-item">
              <div class="label">个人合同收费标准</div>
              <div class="item">
                <div class="num">{{ enterpriseDetail.config.individualContract || '-' }}</div>
                <div class="mb-1">&nbsp;元</div>
              </div>
            </div>
          </div>
          <a-divider direction="vertical" class="h-8" v-if="enterpriseDetail.config.chargeWay === 1" />
          <div class="descriptions-item-box" v-if="enterpriseDetail.config.chargeWay === 1">
            <div class="descriptions-item">
              <div class="label">企业认证收费标准</div>
              <div class="item">
                <div class="num">{{ enterpriseDetail.config.enterpriseAuthentication || '-' }}</div>
                <div class="mb-1">&nbsp;元</div>
              </div>
            </div>
            <div class="descriptions-item">
              <div class="label">个人认证收费标准</div>
              <div class="item">
                <div class="num">{{ enterpriseDetail.config.individualAuthentication || '-' }}</div>
                <div class="mb-1">&nbsp;元</div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </template>
    <div class="service-empty" v-else>
      <img class="service-empty-img" src="@/assets/service-empty.png" />
      <div
        class="service-empty-text"
        v-if="enterpriseDetail.config.econtractFirstOpen === 0 && enterpriseDetail.config.authenticatinStatus === -1"
      >
        暂未开启付费版合同服务，请联系我司工作人员
      </div>
      <div
        class="service-empty-text"
        v-else-if="
          enterpriseDetail.config.authenticatinStatus === -1 ||
          enterpriseDetail.config.authenticatinStatus === 2 ||
          enterpriseDetail.config.authorizationStatus === -1 ||
          enterpriseDetail.config.authorizationStatus === 2
        "
      >
        企业信息认证中，完成认证后开通服务，请稍后
      </div>
      <div class="service-empty-text" v-else-if="enterpriseDetail.config.authenticatinStatus === 0">
        企业信息审核失败，我司工作人员会尽快联系您修改企业信息
      </div>
      <div class="service-empty-text" v-else-if="enterpriseDetail.config.econtractEnabled === 0">
        电子合同服务已关闭，如有疑问请联系我司工作人员
      </div>
    </div>
    <!-- 电子合同业务结束 -->
    <!-- etc和tbox业务展示 -->
    <!-- ETC 开通-->
    <!-- <basic-info-descriptions :data="basicInfo" v-if="currentTab == 2 && enterpriseDetail.config.hrhcEtcEnabled">
      <template #tboxAndetc v-for="(item, index) in basicInfo" :key="index">
        <div class="mb-1 mr-2"
          >{{ item.value }} <a-button size="mini" type="primary" @click="item.method">{{ item.buttonName }}</a-button></div
        >
        <div class="text-xs text-gray-400">{{ item.desc }}</div>
      </template>
    </basic-info-descriptions> -->
    <!-- ETC 未开通-->
    <!-- <div class="box-wrapper" v-if="currentTab == 2 && !enterpriseDetail.config.hrhcEtcEnabled">
      <div class="logo-title-wrapper">
        <span class="title">ETC服务</span>
        <div class="close">暂未开通</div>
      </div>
      <div class="text">如需开通ETC服务请联系启程的工作人员 </div>
      <div class="money-wrapper">
        <div class="money">
          <img src="@/assets/box-money-bg.png" alt="" />
          <div class="msg">
            <div class="money-title">无需充值，无需垫资</div>
            <div class="money-text">让用户自己付通行费</div>
          </div>
        </div>
      </div>
      <div class="money-wrapper">
        <div class="money">
          <img src="@/assets/box-money-bg-1.png" alt="" />
          <div class="msg">
            <div class="money-title">省心省力，坐等分钱</div>
            <div class="money-text">设备方统一运营管理，按比例分润</div>
          </div>
        </div>
      </div>
    </div> -->
    <!-- box 开通-->
    <!-- <div class="box-wrapper" v-if="currentTab == 1 && enterpriseDetail.config.tboxEnabled == 1">
      <div class="logo-title-wrapper">
        <span class="title">车载BOX服务</span>
        <div class="open">已开通</div>
      </div>
      <div class="text">如需关闭车载BOX服务请联系启程的工作人员 </div>
      <a-button size="small" type="primary" @click="goBoxFn">进入【车载BOX业务管理】页</a-button>
    </div> -->
    <!-- box 未开通-->
    <!-- <div class="box-wrapper" v-if="currentTab == 1 && !enterpriseDetail.config.tboxEnabled">
      <div class="logo-title-wrapper">
        <span class="title">车载BOX服务</span>
        <div class="close" style="left: 185px">暂未开通</div>
      </div>
      <div class="text">如需开通ETC服务请联系启程的工作人员 </div>
      <div class="money-wrapper">
        <div class="money">
          <img src="@/assets/box-money-bg-2.png" alt="" />
          <div class="msg">
            <div class="money-title">虚拟钥匙，手机控车</div>
            <div class="money-text">减少取送车等待，提高人车比黑科技</div>
          </div>
        </div>
      </div>
      <div class="money-wrapper">
        <div class="money">
          <img src="@/assets/box-money-bg-3.png" alt="" />
          <div class="msg">
            <div class="money-title">实时位置、轨迹、油量、里程</div>
            <div class="money-text">车辆状态随时一目了然</div>
          </div>
        </div>
      </div>
    </div> -->

    <a-modal v-model:visible="visibleModal" title="充值记录" width="70vw">
      <table-index class="insure-card-table" :table="table" @loadData="loadData">
        <template #voucher="{ record }">
          <a-button type="text" v-if="record.voucher" @click="onPreview(record.vouchers)">查看</a-button>
          <div v-else>-</div>
        </template>
      </table-index>
      <template #footer>
        <a-button @click="onCancelModal">关闭</a-button>
      </template>
    </a-modal>
    <a-image-preview-group v-model:visible="previewVisible" v-model:current="previewCurrent" :maskClosable="false" :srcList="previewList" />
    <OpenLink ref="openLinksRef" @close="openlinkFn" />
  </div>
</template>

<script setup lang="ts">
  import { useFetchTableDataApi, useTable } from '@/hooks/table'
  import basicInfoDescriptions from '../basic-info-descriptions.vue'
  import { Message } from '@arco-design/web-vue'
  import useNavigate from '@/hooks/useNavigate'
  import { usePermission } from '@/hooks/usePermission'
  import OpenLink from '../../modal/open-link.vue'

  import { ref, computed, watch, reactive, onMounted } from 'vue'
  import { getRechargeRecord, saveEnterprise, applyAutoSign } from '@/api/asset/enterprise'

  const { navigateTo } = useNavigate()

  const props = defineProps({
    status: String,
    enterpriseDetail: {
      type: Object,
      default: () => ({}),
    },
  })

  const visibleModal = ref(false)
  const openLinksRef = ref()

  // tabs切换
  // const tabsList = computed(() => {
  //   let arr = [{ label: '电子合同', value: '0' }]
  //   arr.push({ label: '车载BOX', value: '1' })
  //   arr.push({ label: 'ETC', value: '2' })
  //   return arr
  // })
  const currentTab = ref('0')

  const basicInfo = computed(() => {
    const eVal = props.enterpriseDetail.config
    let arr: any[] = []
    switch (currentTab.value) {
      case '0':
        // 电子合同
        arr = [
          {
            label: '开通付费版合同服务',
            value: eVal.userEcontractEnabled === 1 ? '开启' : '关闭',
          },
          {
            label: '支持的服务类型',
            value: eVal.userContractServiceTypeName,
          },
          {
            label: '签约方式',
            slotName: 'signType',
          },
        ]
        break
      case '1':
        // tbox
        arr = [
          {
            label: '车载BOX服务',
            slotName: 'tboxAndetc',
            value: eVal.tboxStatusName,
            // 以下为自定义字段
            buttonName: '进入【车载BOX业务管理】页',
            method: () => {
              usePermission('svms:asstes:equipment:tbox') ? navigateTo(`/assets/device/tbox`) : Message.warning('暂无权限')
            },
            desc: '如果关闭车载BOX服务请联系启程的工作人员',
          },
        ]
        break
      case '2':
        // etc
        arr = [
          {
            label: '好人好车ETC服务',
            slotName: 'tboxAndetc',
            value: eVal.hrhcEtcStatusName,
            buttonName: '进入【ETC业务管理】页',
            method: () => {
              usePermission('svms:asstes:equipment:etc') ? navigateTo(`/assets/device/etc`) : Message.warning('暂无权限')
            },
            desc: '如果关闭ETC服务请联系启程的工作人员',
          },
        ]
        break
    }

    return arr
  })

  const form = ref<any>()
  const formRef = ref()
  watch(
    () => props.enterpriseDetail,
    (newVal) => {
      console.log(newVal, 'newVal')

      form.value = { ...newVal }
    },
    { immediate: true }
  )

  const onApplyFor = () => {
    applyAutoSign().then((res: any) => {
      openLinksRef.value.show(res.result)
    })
  }

  const openModal = () => {
    visibleModal.value = true
  }

  const onCancelModal = () => {
    visibleModal.value = false
  }

  const openlinkFn = async () => {
    emit('updateData')
  }

  const previewVisible = ref(false)
  const previewCurrent = ref(0)
  const previewList = ref<string[]>([])
  const onPreview = (urls: string[]) => {
    previewList.value = []
    previewCurrent.value = 0
    previewVisible.value = true
    urls.forEach((item: any) => {
      previewList.value.push(`${import.meta.env.VITE_BASE_PATH}/uploadFile/image/${item}`)
    })
  }

  const queryParam = reactive({
    epId: props.enterpriseDetail.epId,
  })
  const table = useTable({
    columns: [
      { title: '充值时间', dataIndex: 'createTime', width: 180 },
      {
        title: '充值金额',
        dataIndex: 'rechargeAmount',
        unit: '元',
        width: 180,
      },
      { title: '账户最新余额', dataIndex: 'accountBalance', width: 130, unit: '元' },
      { title: '商户是否支付', dataIndex: 'payTypeName', width: 130 },
      { title: '商户支付凭证', slotName: 'voucher', width: 130 },
    ],
  })

  const loadData = useFetchTableDataApi(table, queryParam, getRechargeRecord)

  const emit = defineEmits(['updateData'])

  const saveFn = () => {
    return new Promise<void>((resolve, reject) => {
      formRef.value.validate((error: any) => {
        if (error) {
          console.log(error)
          reject()
        } else {
          const param = {
            epId: form.value.epId,
            userEcontractEnabled: form.value.config.userEcontractEnabled,
            userContractServiceType: form.value.userContractServiceType,
            signType: form.value.config.signType,
            userServiceTypes: props.enterpriseDetail.userServiceTypes,
            userShortRentChannels: props.enterpriseDetail.userShortRentChannels,
            channelOrderSync: props.enterpriseDetail.channelOrderSync,
            channelOrderMaintenance: props.enterpriseDetail.channelOrderMaintenance,
          }
          saveEnterprise(param).then((res: any) => {
            if (res.code == 200) {
              // 更新 enterpriseDetail 的值
              emit('updateData')
              resolve()
            }
          })
        }
      })
    })
  }

  const isShowLogs = ref(false)
  onMounted(() => {
    loadData().then((res: any) => {
      if (res.data?.length > 0) {
        isShowLogs.value = true
      }
    })
  })

  // const goBoxFn = () => {
  //   usePermission('svms:asstes:equipment:tbox') ? navigateTo(`/value-added/device/car-box-business`) : Message.warning('暂无权限')
  // }

  defineExpose({
    saveFn,
  })
</script>

<style lang="less" scoped>
  .logo-title {
    font-size: 16px;
    font-weight: 600;
    color: #1d2129;
    margin-bottom: 16px;
  }
  .service-box {
    .service-empty {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 500px;

      &-img {
        width: 86px;
        height: 129px;
        margin-bottom: 27px;
      }

      &-text {
        font-size: 16px;
        font-weight: 400;
        color: #1d2129;
      }
    }

    .descriptions-box {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin-top: 16px;
      padding: 20px 20px;
      border: 1px solid #f2f3f5;

      .descriptions-item-box {
        flex: 1;
        justify-content: space-between;
        padding-left: 20px;
        &:nth-child(1) {
          padding-left: 0;
        }
        .descriptions-item {
          padding-bottom: 16px;
          &:nth-child(2) {
            padding-bottom: 0;
          }
          .label,
          .item {
            font-size: 12px;
            font-weight: 400;
            color: #4e5969;
          }

          .item {
            display: flex;
            align-items: flex-end;
            font-size: 12px;

            .num {
              font-size: 20px;
              font-weight: 600;
              color: #1d2129;
              &.blue {
                color: rgba(24, 144, 255, 1);
              }
            }
          }
        }
      }

      .descriptions-button {
        width: 100%;
        text-align: end;
      }
    }

    .service-view {
      :deep(.arco-descriptions-size-medium .arco-descriptions-item-label-block),
      :deep(.arco-descriptions-size-medium .arco-descriptions-item-value-block) {
        padding-bottom: 0;
      }
    }
    .box-wrapper {
      display: flex;
      justify-content: flex-start;
      flex-direction: column;
      align-items: flex-start;
      padding: 74px 0 0 57px;
      width: 100%;
      height: 521px;
      background-image: url('../../../../../assets/box-bg.png') !important;
      background-size: 100% 100%;
      .logo-title-wrapper {
        position: relative;
        .title {
          font-weight: 500;
          font-size: 32px;
          color: #1d2129;
          line-height: 40px;
        }
        .open,
        .close {
          position: absolute;
          top: -2px;
          left: 185px;
          display: flex;
          justify-content: center;
          align-items: center;
          font-weight: 600;
          font-size: 12px;
          color: #ffffff;
          line-height: 12px;
          width: 50px;
          height: 19px;
          background: linear-gradient(222deg, #ff7a66 0%, #ff5b60 100%);
          border-radius: 60px;
        }
        .close {
          left: 115px;
          color: #919aa5;
          width: 64px;
          background: linear-gradient(222deg, #f2f3f5 0%, #dbdbdb 100%);
        }
      }
      .text {
        font-weight: 400;
        font-size: 14px;
        color: #919aa5;
        line-height: 22px;
        margin: 12px 0 32px 0;
      }
      .money-wrapper {
        .money {
          display: flex;
          align-items: center;
          margin-top: 24px;
          img {
            width: 54px;
            height: 54px;
          }
          .money-title {
            font-weight: 500;
            font-size: 16px;
            color: #1d2129;
            line-height: 22px;
            margin-bottom: 3px;
          }
          .money-text {
            font-weight: 400;
            font-size: 12px;
            color: #919aa5;
            line-height: 22px;
          }
        }
      }
    }
  }
</style>
